package com.atguigu.mybatisplus.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * 源数据类 ，配置 创建时间，更新时间填充等·
 * @Auther 赵乾坤
 * @Date 2021-10-28 22:33
 */
@Slf4j//日志
@Component//包扫描
public class MyMetaObjectHandler implements MetaObjectHandler {

    /**
     * 插入填充
     * @param metaObject 元数据
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("start insert fill ....");
        // 1元数据 2.字段名 3类型 4  时间
        this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
        this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());

        // 优化方案1
        // 判断是否有具备author属性 如果有填充
        boolean hasAuthor = metaObject.hasSetter("author");
        if(hasAuthor){
            log.info("start insert fill author....");
            this.strictInsertFill(metaObject, "author", String.class, "Helen");
        }

        // 优化方案2
        // 判断age是否赋值
        Object age = this.getFieldValByName("age", metaObject);
        if(age == null){
            log.info("start insert fill age....");
            this.strictInsertFill(metaObject, "age", Integer.class, 18);
        }

    }

    /**
     * 更新填充
     * @param metaObject 元数据
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("start update fill ....");
        this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
    }
}


